package com.itmck.common.gloable;


import com.itmck.common.bo.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/11/3 10:33
 * <p>
 * 自定义全局异常处理器
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {


    @ExceptionHandler(value = NullPointerException.class)
    public ApiResponse<String> responseException(NullPointerException exception) {
        log.error("空指针异常", exception);
        return ApiResponse.error("空指针异常", "500");
    }


    @ExceptionHandler(value = BusinessException.class)
    public ApiResponse<String> businessHandler(BusinessException exception) {
        log.error("业务异常", exception);
        return ApiResponse.error(exception.getMessage(), exception.getCode());
    }

    @ExceptionHandler(value = Exception.class)
    public ApiResponse<String> defaultHandler(Exception exception) {
        log.error("系统异常", exception);

        Class<? extends Exception> aClass = exception.getClass();
        if (aClass.equals(ConstraintViolationException.class)) {
            return ApiResponse.error(exception.getMessage(), "400");
        }


        return ApiResponse.error("系统异常", "500");
    }
}